package com.fishingwithme.android.ui.screens.auth

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.fishingwithme.android.R
import com.fishingwithme.android.navigation.FishingNavigation
import com.fishingwithme.android.ui.theme.AppDimensions
import com.fishingwithme.android.ui.viewmodels.RegisterViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RegisterScreen(
    navController: NavController,
    viewModel: RegisterViewModel = hiltViewModel()
) {
    val uiState by viewModel.uiState.collectAsState()
    var passwordVisible by remember { mutableStateOf(false) }
    var confirmPasswordVisible by remember { mutableStateOf(false) }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("") },
                navigationIcon = {
                    IconButton(onClick = { navController.popBackStack() }) {
                        Icon(
                            Icons.Default.ArrowBack,
                            contentDescription = stringResource(R.string.back)
                        )
                    }
                }
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .verticalScroll(rememberScrollState()),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            if (uiState.isRegistered) {
                // Registration success screen
                RegistrationSuccessScreen(navController)
            } else {
                // Registration form
                RegistrationForm(
                    uiState = uiState,
                    passwordVisible = passwordVisible,
                    confirmPasswordVisible = confirmPasswordVisible,
                    onPasswordVisibilityChange = { passwordVisible = it },
                    onConfirmPasswordVisibilityChange = { confirmPasswordVisible = it },
                    onUsernameChange = { viewModel.setUsername(it) },
                    onPasswordChange = { viewModel.setPassword(it) },
                    onConfirmPasswordChange = { viewModel.setConfirmPassword(it) },
                    onEmailChange = { viewModel.setEmail(it) },
                    onNicknameChange = { viewModel.setNickname(it) },
                    onPrivacyPolicyChecked = { viewModel.setPrivacyPolicyChecked(it) },
                    onUserAgreementChecked = { viewModel.setUserAgreementChecked(it) },
                    onRegisterClick = { viewModel.register() },
                    onClearError = { viewModel.clearError() },
                    navController = navController
                )
            }
        }
    }
}

@Composable
fun RegistrationForm(
    uiState: com.fishingwithme.android.ui.viewmodels.RegisterUiState,
    passwordVisible: Boolean,
    confirmPasswordVisible: Boolean,
    onPasswordVisibilityChange: (Boolean) -> Unit,
    onConfirmPasswordVisibilityChange: (Boolean) -> Unit,
    onUsernameChange: (String) -> Unit,
    onPasswordChange: (String) -> Unit,
    onConfirmPasswordChange: (String) -> Unit,
    onEmailChange: (String) -> Unit,
    onNicknameChange: (String) -> Unit,
    onPrivacyPolicyChecked: (Boolean) -> Unit,
    onUserAgreementChecked: (Boolean) -> Unit,
    onRegisterClick: () -> Unit,
    onClearError: () -> Unit,
    navController: NavController
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(AppDimensions.SPACING_16),
        shape = RoundedCornerShape(AppDimensions.ROUNDED_CORNER_12),
        elevation = CardDefaults.cardElevation(defaultElevation = 6.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(AppDimensions.SPACING_24),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(
                text = stringResource(R.string.register_title),
                style = MaterialTheme.typography.headlineSmall,
                modifier = Modifier.padding(bottom = AppDimensions.SPACING_24)
            )

            // Username Field
            OutlinedTextField(
                value = uiState.username,
                onValueChange = onUsernameChange,
                label = { Text(stringResource(R.string.register_username_hint)) },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = AppDimensions.SPACING_16),
                singleLine = true,
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
                leadingIcon = {
                    Icon(
                        imageVector = Icons.Default.Person,
                        contentDescription = null
                    )
                },
                shape = RoundedCornerShape(AppDimensions.ROUNDED_CORNER_8)
            )

            // Password Field
            OutlinedTextField(
                value = uiState.password,
                onValueChange = onPasswordChange,
                label = { Text(stringResource(R.string.register_password_hint)) },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = AppDimensions.SPACING_16),
                singleLine = true,
                visualTransformation = if (passwordVisible) {
                    VisualTransformation.None
                } else {
                    PasswordVisualTransformation()
                },
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
                leadingIcon = {
                    Icon(
                        imageVector = Icons.Default.Lock,
                        contentDescription = null
                    )
                },
                trailingIcon = {
                    val image = if (passwordVisible) {
                        Icons.Filled.Visibility
                    } else {
                        Icons.Filled.VisibilityOff
                    }

                    IconButton(onClick = { onPasswordVisibilityChange(!passwordVisible) }) {
                        Icon(imageVector = image, contentDescription = null)
                    }
                },
                shape = RoundedCornerShape(AppDimensions.ROUNDED_CORNER_8)
            )

            // Confirm Password Field
            OutlinedTextField(
                value = uiState.confirmPassword,
                onValueChange = onConfirmPasswordChange,
                label = { Text(stringResource(R.string.register_confirm_password_hint)) },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = AppDimensions.SPACING_16),
                singleLine = true,
                visualTransformation = if (confirmPasswordVisible) {
                    VisualTransformation.None
                } else {
                    PasswordVisualTransformation()
                },
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
                leadingIcon = {
                    Icon(
                        imageVector = Icons.Default.Lock,
                        contentDescription = null
                    )
                },
                trailingIcon = {
                    val image = if (confirmPasswordVisible) {
                        Icons.Filled.Visibility
                    } else {
                        Icons.Filled.VisibilityOff
                    }

                    IconButton(onClick = { onConfirmPasswordVisibilityChange(!confirmPasswordVisible) }) {
                        Icon(imageVector = image, contentDescription = null)
                    }
                },
                shape = RoundedCornerShape(AppDimensions.ROUNDED_CORNER_8)
            )

            // Email Field
            OutlinedTextField(
                value = uiState.email,
                onValueChange = onEmailChange,
                label = { Text(stringResource(R.string.register_email_hint)) },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = AppDimensions.SPACING_16),
                singleLine = true,
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),
                leadingIcon = {
                    Icon(
                        imageVector = Icons.Default.Email,
                        contentDescription = null
                    )
                },
                shape = RoundedCornerShape(AppDimensions.ROUNDED_CORNER_8)
            )

            // Nickname Field
            OutlinedTextField(
                value = uiState.nickname,
                onValueChange = onNicknameChange,
                label = { Text(stringResource(R.string.register_nickname_hint)) },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = AppDimensions.SPACING_24),
                singleLine = true,
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
                leadingIcon = {
                    Icon(
                        imageVector = Icons.Default.AccountCircle,
                        contentDescription = null
                    )
                },
                shape = RoundedCornerShape(AppDimensions.ROUNDED_CORNER_8)
            )

            // Privacy Policy and User Agreement Checkboxes
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = AppDimensions.SPACING_24),
                verticalArrangement = Arrangement.spacedBy(AppDimensions.SPACING_4)
            ) {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Checkbox(
                        checked = uiState.isPrivacyPolicyChecked,
                        onCheckedChange = onPrivacyPolicyChecked
                    )
                    TextButton(onClick = {
                        navController.navigate("${FishingNavigation.AGREEMENT_POLICY}?type=AD_PP")
                    }) {
                        Text(stringResource(R.string.view_and_agree_policy))
                    }
                }

                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Checkbox(
                        checked = uiState.isUserAgreementChecked,
                        onCheckedChange = onUserAgreementChecked
                    )
                    TextButton(onClick = {
                        navController.navigate("${FishingNavigation.AGREEMENT_POLICY}?type=AD_UA")
                    }) {
                        Text(stringResource(R.string.view_and_agree_agreement))
                    }
                }
            }

            // Register Button
            Button(
                onClick = onRegisterClick,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = AppDimensions.SPACING_16)
                    .height(50.dp),
                enabled = !uiState.isLoading,
                shape = RoundedCornerShape(AppDimensions.ROUNDED_CORNER_8)
            ) {
                if (uiState.isLoading) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(AppDimensions.ICON_SIZE_20),
                        color = MaterialTheme.colorScheme.onPrimary
                    )
                } else {
                    Text(stringResource(R.string.register_button))
                }
            }

            // Error Message
            uiState.error?.let { error ->
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = AppDimensions.SPACING_16),
                    colors = CardDefaults.cardColors(
                        containerColor = MaterialTheme.colorScheme.errorContainer
                    )
                ) {
                    Text(
                        text = error,
                        modifier = Modifier.padding(AppDimensions.SPACING_16),
                        color = MaterialTheme.colorScheme.onErrorContainer,
                        textAlign = TextAlign.Center
                    )
                }
            }

            // Login Link
            TextButton(
                onClick = {
                    navController.navigate(FishingNavigation.LOGIN) {
                        popUpTo(FishingNavigation.REGISTER) { inclusive = true }
                    }
                }
            ) {
                Text(
                    text = stringResource(R.string.register_already_have_account) + " " + stringResource(R.string.register_login_link),
                    style = MaterialTheme.typography.bodyMedium
                )
            }
        }
    }
}

@Composable
fun RegistrationSuccessScreen(navController: NavController) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(AppDimensions.SPACING_16),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(AppDimensions.SPACING_16),
            shape = RoundedCornerShape(AppDimensions.ROUNDED_CORNER_12),
            elevation = CardDefaults.cardElevation(defaultElevation = 6.dp)
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(AppDimensions.SPACING_32),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Icon(
                    imageVector = Icons.Default.CheckCircle,
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.primary,
                    modifier = Modifier
                        .size(80.dp)
                        .padding(bottom = AppDimensions.SPACING_24)
                )

                Text(
                    text = stringResource(R.string.register_success_title),
                    style = MaterialTheme.typography.headlineSmall,
                    modifier = Modifier.padding(bottom = AppDimensions.SPACING_16)
                )

                Text(
                    text = stringResource(R.string.register_success_message),
                    style = MaterialTheme.typography.bodyMedium,
                    textAlign = TextAlign.Center,
                    modifier = Modifier.padding(bottom = AppDimensions.SPACING_32)
                )

                Button(
                    onClick = {
                        navController.navigate(FishingNavigation.LOGIN) {
                            popUpTo(FishingNavigation.LOGIN) { inclusive = true }
                        }
                    },
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(50.dp),
                    shape = RoundedCornerShape(AppDimensions.ROUNDED_CORNER_8)
                ) {
                    Text(stringResource(R.string.register_success_button))
                }
            }
        }
    }
}